import { Pdf2Image } from './pdf2image'
import { Editor } from 'tinymce'
import { ElLoading } from 'element-plus'
import { ossSaveMinioFileUsingPost } from '@/api/4a/osswenjianshangchuan'

// `设置常量，分别定义canvas的dpi, pdf的dpi以及图片缩放比例`
const CANVASDPI = 72
const PDFDPI = 96
const SCALE = 2

// 处理PDF上传和转换
export async function uploadPdfHandler(editor: Editor, file: File): Promise<void> {
  const loading = ElLoading.service({
    text: '正在处理PDF文件...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let url = ''

    const result = await ossSaveMinioFileUsingPost({
      body: {},
      file
    })

    if (result.code === 0) {
      url = result.data?.path || ''
    } else {
      editor.notificationManager.open({
        text: '文件上传失败',
        type: 'error'
      })
      return
    }

    const pdf2img = await Pdf2Image.open(url)
    const totalPages = pdf2img.numPages()
    for (let i = 1; i <= totalPages; i++) {
      let c: HTMLCanvasElement | null = null
      const url = await pdf2img.getImageDataUrl(i, {
        scale: (PDFDPI / CANVASDPI) * SCALE,
        callback: ({ canvas }) => {
          c = canvas
        }
      })
      // 插入图片到编辑器
      editor.insertContent(`
        <div class="pdf-page">
          <img width="${c?.width / 2}" height="${c?.height / 2}" src="${url}" ></img>
        </div>
      `)
    }
  } catch (err) {
    editor.notificationManager.open({
      text: 'PDF处理失败',
      type: 'error'
    })
  } finally {
    loading.close()
  }
}
